//
//  DrawingBoardView.swift
//  Game
//
//  Created by woniu on 2025/9/11.
//

import UIKit

class DrawingBoardView: UIView {

    public var onCancelBlock: (()->())?
	// toolbar
	private let toolbar = UIView()
	private let colors: [UIColor] = [.white, .systemBlue, .systemRed, .systemYellow]
	private var colorButtons: [UIButton] = []
	private var undoButton = UIButton(type: .system)
	private var clearButton = UIButton(type: .system)
	private var closeButton = UIButton(type: .system)

	// drawing
	private var currentColor: UIColor = .systemRed
	private let lineWidth: CGFloat = 3.0
	private var currentPath: UIBezierPath?
	private var pathLayers: [CAShapeLayer] = []

	override init(frame: CGRect) {
		super.init(frame: frame)
		commonInit()
	}
	required init?(coder: NSCoder) { super.init(coder: coder); commonInit() }

	private func commonInit() {
		backgroundColor = .clear
		setupToolbar()
		isMultipleTouchEnabled = false
	}

	private func setupToolbar() {
        toolbar.backgroundColor = .black
        toolbar.translatesAutoresizingMaskIntoConstraints = false
		addSubview(toolbar)
        toolbar.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(10)
            make.height.equalTo(64)
            make.width.equalTo(350)
            make.centerX.equalToSuperview()
        }
        //关闭
        closeButton.setImage(UIImage(named: "关闭_白色"), for: .normal)
		closeButton.addTarget(self, action: #selector(closeTapped), for: .touchUpInside)
        closeButton.tintColor = .white
		toolbar.addSubview(closeButton)
        closeButton.snp.makeConstraints { make in
            make.right.equalToSuperview().offset(-12)
            make.top.bottom.equalToSuperview()
            make.width.equalTo(45)
        }
        
        //清除
        clearButton.setImage(UIImage(named: "擦除_白色"), for: .normal)
		clearButton.addTarget(self, action: #selector(clearTapped), for: .touchUpInside)
        clearButton.tintColor = .white
		toolbar.addSubview(clearButton)
        clearButton.snp.makeConstraints { make in
            make.right.equalTo(closeButton.snp.left).offset(-5)
            make.top.bottom.equalToSuperview()
            make.width.equalTo(45)
        }
        
        //撤销
        undoButton.setImage(UIImage(named: "撤销_白色"), for: .normal)
		undoButton.addTarget(self, action: #selector(undoTapped), for: .touchUpInside)
        undoButton.tintColor = .white
		toolbar.addSubview(undoButton)
        undoButton.snp.makeConstraints { make in
            make.right.equalTo(clearButton.snp.left).offset(-5)
            make.top.bottom.equalToSuperview()
            make.width.equalTo(45)
        }
        
        //
        var prev: UIView = undoButton
        for (index,c) in colors.enumerated(){
            let btn = UIButton(type: .system)
            btn.backgroundColor = c
            btn.layer.cornerRadius = 16
            btn.layer.borderWidth = 1
            btn.layer.borderColor = UIColor.white.withAlphaComponent(0.25).cgColor
            btn.addTarget(self, action: #selector(colorTapped(_:)), for: .touchUpInside)
            toolbar.addSubview(btn)
            btn.snp.makeConstraints { make in
                if index == 0{
                    make.right.equalTo(prev.snp.left).offset(-25)
                }else{
                    make.right.equalTo(prev.snp.left).offset(-5)
                }
                make.size.equalTo(CGSize(width: 32, height: 32))
                make.centerY.equalToSuperview()
            }
            prev = btn
            colorButtons.append(btn)
        }

		selectColor(.systemRed)
	}

	@objc private func colorTapped(_ sender: UIButton) {
		guard let idx = colorButtons.firstIndex(of: sender) else { return }
		selectColor(colors[idx])
	}

	private func selectColor(_ c: UIColor) {
		currentColor = c
		// indicate selection via border
		for (i, b) in colorButtons.enumerated() {
			b.layer.borderWidth = (colors[i] == c) ? 3 : 1
			b.layer.borderColor = (colors[i] == c) ? UIColor.green.cgColor : UIColor.white.withAlphaComponent(0.25).cgColor
		}
	}

	@objc private func undoTapped() {
		guard let last = pathLayers.popLast() else { return }
		last.removeFromSuperlayer()
	}

	@objc private func clearTapped() {
		for l in pathLayers { l.removeFromSuperlayer() }
		pathLayers.removeAll()
	}

	@objc private func closeTapped() {
		print("did print")
        clearTapped()
        onCancelBlock?()
	}

	// MARK: - Touch drawing
	override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
		guard let t = touches.first else { return }
		let p = t.location(in: self)
		// ignore touches in toolbar area
		if p.y <= toolbar.frame.maxY { return }
		let path = UIBezierPath()
		path.lineWidth = lineWidth
		path.lineCapStyle = .round
		path.move(to: p)
		currentPath = path
		let layer = CAShapeLayer()
		layer.path = path.cgPath
		layer.strokeColor = currentColor.cgColor
		layer.fillColor = UIColor.clear.cgColor
		layer.lineWidth = lineWidth
		layer.lineCap = .round
		layer.zPosition = 1
		self.layer.addSublayer(layer)
		pathLayers.append(layer)
	}

	override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
		guard let t = touches.first, let path = currentPath else { return }
		let p = t.location(in: self)
		if p.y <= toolbar.frame.maxY { return }
		path.addLine(to: p)
		if let layer = pathLayers.last { layer.path = path.cgPath; layer.strokeColor = currentColor.cgColor }
	}

	override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
		currentPath = nil
	}

	override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
		currentPath = nil
	}

}
